import React, { Component } from 'react'
import request from '../util/request'
import moment from 'moment'; 
import IsLogin from '../util/isLogin'

class Home extends Component {
    state = {
        list:[],
        uid:''
    }
    componentDidMount(){
        let uid = localStorage.getItem('uid');

        console.log(uid);

        this.setState({uid});
        this.getList();
        
    }

    getList(){
        request.get('/api/blog').then(res => {
            if(res.code === 1){
                this.setState({
                    list:res.data
                })
            }
        })
    }
    render() {
        let {list,uid} = this.state;
        return (
            <div>
                <div className="list">
                    <ul>
                        {list.length && list.map((item) => <li key={item.id}>{item.title}-{moment(item.create_time).format('YYYY-MM-DD')}-{item.username}
                        {uid==item.uid && <div>
                            <button onClick={() => this.goAdd(item)}>编辑</button>
                            <button onClick={() => {this.del(item.id)}}>删除</button>
                        </div>}
                        
                    </li>)}
                    </ul>
                </div>
                <button onClick={()=>this.goAdd()}>发表博客</button>
            </div>
        )
    }

    goAdd = (item) => {
        if(item){
            this.props.history.push(`/add`,{id:item.id});
            localStorage.setItem("obj",JSON.stringify(item));
        }else{
            this.props.history.push('/add')
        }
    }

    del = (id) => {
        request.delete(`/api/blog/${id}`).then(res =>{
            console.log(res);
            if(res.code === 1){
                this.getList();
            }
        })
    }
}

export default IsLogin(Home)